package controller

import (
	"alan-snippet/internal/dto"
	"alan-snippet/internal/middleware"
	"alan-snippet/internal/response"
	"alan-snippet/internal/service"

	"github.com/gin-gonic/gin"
)

func RegisterUser(c *gin.Context) {
	// resolve JSON parm
	var register dto.RegisterRequestDTO
	err := c.ShouldBindJSON(&register)
	if err != nil {
		response.Fail(c, response.ErrCodeParmResolve, nil, err.Error())
		return
	}

	// call service
	user, err := service.RegisterUser(&register)
	if err != nil {
		response.Fail(c, response.ErrCodeInternal, nil, err.Error())
		return
	}

	// encapsulate DTO
	res := dto.RegisterResponseDTO{
		Id:    user.ID,
		Email: user.Email,
	}

	response.OkWithData(c, res)
}

func LoginUser(c *gin.Context) {
	// resolve JSON parm
	var loginDTO dto.LoginRequestDTO
	err := c.ShouldBindJSON(&loginDTO)
	if err != nil {
		response.Fail(c, response.ErrCodeParmResolve, nil, err.Error())
		return
	}

	// service
	user, err := service.LoginUser(&loginDTO)
	if err != nil {
		response.Fail(c, response.ErrCodeInternal, nil, err.Error())
		return
	}
	userInfo := struct {
		Id    uint   `json:"id"`
		Email string `json:"email"`
	}{
		Id:    user.ID,
		Email: user.Email,
	}

	// gen token
	token, err := middleware.GenerateToken(user.ID)
	if err != nil {
		response.Fail(c, response.ErrCodeInternal, nil, err.Error())
		return
	}

	res := &dto.LoginResponseDTO{
		User:  userInfo,
		Token: token,
	}
	response.OkWithData(c, res)
}
